const app = getApp()
import { getProjectMemberDetail, addProjectMemberSpace, deleteProjectMemberSpace, deleteProjectMember } from '../../../../api/index'

Page({
  data: {
    safeBottom: 0,
    projectId: '',
    userId: '',
    role: '',
    detail: {},
    spaceList: []
  },
  addSpace () {
    this.setData({ showSpaceModal: true })
  },
  close () {
    this.setData({ showSpaceModal: false })
  },
  async delMember () {
    try {
      const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除该成员吗？' })
      if (confirm) {
        await deleteProjectMember({ projectId: this.data.projectId, memberUserId: this.data.userId })
        wx.showToast({ title: '删除成功！', icon: 'none' })
        wx.$nav.navigateBack()
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async delSpace ({ currentTarget: { dataset: { item } } }) {
    try {
      const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除该空间吗？' })
      if (confirm) {
        await deleteProjectMemberSpace({ projectId: this.data.projectId, memberUserId: this.data.userId, spaceId: item.spaceId })
        wx.showToast({ title: '删除成功！', icon: 'none' })
        this.getDetail()
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async confirm ({ detail }) {
    try {
      let query = {
        projectId: this.data.projectId,
        memberUserId: this.data.userId
      }
      let ids = detail.map(item => { return item.spaceId })
      query.spaceIdList = ids
      await addProjectMemberSpace({ ...query })
      wx.showToast({ title: '添加成功！', icon: 'none' })
      this.setData({ showSpaceModal: false })
      this.getDetail()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getDetail () {
    try {
      const { ResultSet } = await getProjectMemberDetail({ projectId: this.data.projectId, memberUserId: this.data.userId })
      this.setData({ detail: ResultSet.userData.detail })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ projectId, userId, role }) {
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    this.setData({ safeBottom: screenHeight - bottom, projectId: projectId, userId: userId, role: parseInt(role) })
    this.getDetail()
  }
})